package cn.cxq.learning.array;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;

public class OurDistance {
    long count;

    @Test
    public void test() {
        System.out.println(Arrays.toString(solve(5,new Point[]{new Point(2,5),new Point(5,3),new Point(5,4),new Point(5,1)})));
    }

    public long[] solve(int n, Point[] edge) {
        // write code here
        int[][] path = new int[n][n];

        for (Point e : edge) {
            path[e.x - 1][e.y - 1] = 1;
            path[e.y - 1][e.x - 1] = 1;
        }

        long[] result = new long[n];

        for (int i = 0; i < n; i++) {

            boolean[] visited = new boolean[n];

            visited[i] = true;

            count = 0;

            bfs(i, visited, path, 1);

            result[i] = count;
        }

        return result;
    }

    private void bfs(int node, boolean[] visited, int[][] path, int step) {

        ArrayList<Integer> nextNodes = new ArrayList<>();

        for (int i = 0; i < path[node].length; i++) {
            if (path[node][i] == 1 && !visited[i]) {
                nextNodes.add(i);
                visited[i] = true;
                count += step;
            }
        }

        for (int nextNode : nextNodes) {
            bfs(nextNode, visited, path, step + 1);
        }
    }
}

class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
